package com.gl.emms.whale.db;

import java.util.ArrayList;
import java.util.List;

import com.gl.emms.whale.util.ApplacationInfo;
import com.gl.emms.whale.util.SystemMsgEntity;

import android.R.integer;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class MessageDB {
	private SQLiteDatabase db;

	public MessageDB(Context context) {
		db = context.openOrCreateDatabase(ApplacationInfo.DBNAME,
				Context.MODE_PRIVATE, null);
	}

	public void saveMsg(SystemMsgEntity entity) {
		db.execSQL("CREATE table IF NOT EXISTS MSG"
				+ " (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, date TEXT, fromwhere TEXT, towhere TEXT, message TEXT, img INTEGER, isreaded INTEGER);");


		db.execSQL(
				"insert into MSG"
						+ " (title,date,fromwhere,towhere,message,img,isreaded) values(?,?,?,?,?,?,?)",
						new Object[] { entity.getMsgTitle(), entity.getDate(),entity.getMsgFrom(),entity.getMsgTo(),entity.getMessage(),entity.getImg(),
								entity.getIsreaded() });

	}

	public List<SystemMsgEntity> getMsg() {
		List<SystemMsgEntity> list = new ArrayList<SystemMsgEntity>();
		db.execSQL("CREATE table IF NOT EXISTS MSG"
				+ " (_id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT, date TEXT,fromwhere TEXT,towhere TEXT,message TEXT,img INTEGER,isreaded INTEGER)");
		Cursor c = db.rawQuery("SELECT * from MSG", null);
		while (c.moveToNext()) {

			int msgId = c.getInt(c.getColumnIndex("_id"));
			String title = c.getString(c.getColumnIndex("title"));
			String date = c.getString(c.getColumnIndex("date"));
			String from = c.getString(c.getColumnIndex("fromwhere"));
			String to = c.getString(c.getColumnIndex("towhere"));
			String message = c.getString(c.getColumnIndex("message"));
			int img = c.getInt(c.getColumnIndex("img"));
			int isreaded = c.getInt(c.getColumnIndex("isreaded"));

			SystemMsgEntity entity = new SystemMsgEntity(msgId,title, date, from,to,message,img,isreaded);
			list.add(entity);
		}
		c.close();
		return list;
	}
	public void removeMsg(int id) {
		db.execSQL("CREATE table IF NOT EXISTS MSG"
				+ " (_id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT, date TEXT,fromwhere TEXT,towhere TEXT,message TEXT,img INTEGER,isreaded INTEGER)");
		db.execSQL("DELETE from MSG where _id = ?",new Object[] { id });
	}
	public int getMaxId() {
		db.execSQL("CREATE table IF NOT EXISTS MSG"
				+ " (_id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT, date TEXT,fromwhere TEXT,towhere TEXT,message TEXT,img INTEGER,isreaded INTEGER)");
		String strSql = " Select  seq From sqlite_sequence  Where name = 'MSG'";

		Cursor mCursor = db.rawQuery(strSql, null);
		int maxId = 0;
		if(mCursor.moveToNext())
		{
			maxId = mCursor.getInt(mCursor.getColumnIndex("seq")); 
		}
		return maxId;
	}

	public void close() {
		if (db != null)
			db.close();
	}
}
